<template>
  <view class="customize-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="page-title">{{ isEditMode ? "编辑模式" : "定制图片" }}</text>
      <view class="complete-btn" @tap="completeDesign">
        <text class="complete-text">完成作品</text>
      </view>
    </view>

    <!-- 编辑模式工具栏 -->
    <view class="edit-toolbar" v-if="isEditMode">
      <view class="toolbar-section">
        <button
          class="tool-btn"
          @click="sendToBack"
          :disabled="!selectedFeature"
        >
          <text class="tool-icon">⬇️</text>
          <text class="tool-label">后置</text>
        </button>
        <button
          class="tool-btn"
          @click="bringToFront"
          :disabled="!selectedFeature"
        >
          <text class="tool-icon">⬆️</text>
          <text class="tool-label">前置</text>
        </button>
      </view>
      <view class="toolbar-section">
        <button class="tool-btn primary" @click="exitEditMode">
          <text class="tool-icon">✓</text>
          <text class="tool-label">完成</text>
        </button>
      </view>
    </view>

    <view class="content">
      <!-- 左侧标题 -->
      <view class="side-title">
        <text class="title-text">人脸娃娃娃娃</text>
      </view>

      <!-- 头像预览区域 -->
      <view class="avatar-preview-wrapper">
        <view class="avatar-preview" @tap="enterEditMode">
          <!-- 底图 -->
          <image
            v-if="selectedAvatar"
            :src="selectedAvatar"
            class="avatar-img"
            mode="aspectFit"
          />
          <view v-else class="default-head">
            <image
              src="/static/images/default-design.png"
              class="default-head-img"
              mode="aspectFit"
            />
          </view>

          <!-- 拖拽的五官组件 -->
          <view
            v-for="(feature, index) in placedFeatures"
            :key="feature.configId"
            class="draggable-feature"
            :class="{
              active:
                selectedFeature &&
                selectedFeature.configId === feature.configId,
              dragging:
                draggingFeature &&
                draggingFeature.configId === feature.configId,
            }"
            :style="{
              left: feature.offsetX + 'px',
              top: feature.offsetY + 'px',
              transform: `translate(-50%, -50%) rotate(${feature.rotation}deg) scale(${feature.scale})`,
              zIndex: feature.layerOrder,
              opacity: feature.visible ? feature.opacity : 0.3,
            }"
            @touchstart="onFeatureTouchStart($event, feature)"
            @touchmove="onFeatureTouchMove($event, feature)"
            @touchend="onFeatureTouchEnd($event, feature)"
            @tap="selectFeature(feature)"
          >
            <image
              v-if="feature.imageUrl"
              :src="feature.imageUrl"
              class="feature-image"
              mode="aspectFit"
            />
            <text v-else class="feature-placeholder">{{
              feature.featureName
            }}</text>

            <!-- 选中时的控制点 -->
            <view
              v-if="
                selectedFeature && selectedFeature.configId === feature.configId
              "
              class="feature-controls"
              @touchstart="onControlTouchStart"
              @touchmove="handleScaleMove"
              @touchend="handleScaleEnd"
            >
              <!-- 左上角删除按钮 -->
              <view
                class="control-point delete-point"
                :style="{
                  position: 'absolute',
                  top: `${-15 * feature.scale}rpx`,
                  left: `${-15 * feature.scale}rpx`,
                }"
                @touchstart.prevent="onDeleteFeature($event, feature)"
              >
                <image
                  src="/static/image/close.png"
                  class="control-icon"
                  mode="aspectFit"
                />
              </view>
              <!-- 右下角缩放旋转按钮 -->
              <view
                class="control-point scale-rotate-point"
                :style="{
                  position: 'absolute',
                  bottom: `${-15 * feature.scale}rpx`,
                  right: `${-15 * feature.scale}rpx`,
                }"
                @touchstart.prevent="onScaleStart($event, feature)"
              >
                <image
                  src="/static/image/suofang.png"
                  class="control-icon"
                  mode="aspectFit"
                />
              </view>
            </view>

            <!-- 缩放比例提示 -->
            <view v-if="scaleTip" class="scale-tip">
              <text class="scale-tip-text">{{ scaleTip }}</text>
            </view>
          </view>

          <!-- 右侧功能按钮 -->
          <view class="side-functions">
            <view class="function-item" @tap="previewCustomization">
              <text class="function-icon">👁️</text>
              <text class="function-label">预览</text>
            </view>
            <view class="function-item" @tap="showHelp">
              <text class="function-icon">❓</text>
              <text class="function-label">帮助</text>
            </view>
            <view class="function-item" @tap="shareCustomization">
              <text class="function-icon">🔗</text>
              <text class="function-label">分享</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 定制选项区域 -->
      <view class="customize-options">
        <!-- 特征类别选择 -->
        <scroll-view scroll-x="true" class="feature-tabs">
          <view
            v-for="(feature, index) in featureCategories"
            :key="index"
            class="feature-tab"
            :class="{ active: currentFeatureIndex === index }"
            @tap="switchFeature(index)"
          >
            <text class="feature-tab-text">{{ feature.name }}</text>
            <uni-load-more
              v-if="loading && currentFeatureIndex === index"
              :status="'loading'"
              :icon-size="14"
              :content-size="12"
            ></uni-load-more>
          </view>
        </scroll-view>

        <!-- 特征选项列表 -->
        <scroll-view
          scroll-x="true"
          class="feature-options"
          v-if="!loading || currentFeatureOptions.length > 0"
        >
          <view
            v-for="(option, index) in currentFeatureOptions"
            :key="option.id || index"
            class="feature-option"
            :class="{ active: selectedOptions[currentFeatureIndex] === index }"
            @tap="selectFeatureOption(index)"
          >
            <view class="option-preview">
              <image
                v-if="option.featureImageUrl"
                :src="option.featureImageUrl"
                class="option-img"
                mode="aspectFit"
              />
              <text v-else class="option-placeholder">{{
                option.featureName
              }}</text>
            </view>
            <text class="option-name">{{ option.featureName }}</text>
          </view>
          <view v-if="currentFeatureOptions.length === 0" class="empty-options">
            暂无相关样式
          </view>
        </scroll-view>
        <view v-else class="loading-container">
          <uni-load-more
            :status="'loading'"
            :icon-size="24"
            :content-size="14"
          ></uni-load-more>
          <text>正在加载样式...</text>
        </view>

        <!-- 清空按钮 -->
        <view class="clear-btn" @tap="clearDesign">
          <text class="clear-text">清空</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import http from "@/utils/http.js";

// 页面参数
const avatarId = ref("");
const selectedAvatar = ref("");

// 定制状态
const isEditMode = ref(false);
const currentFeatureIndex = ref(0);
const selectedOptions = ref([]);
const loading = ref(false);

// 拖拽编辑状态
const placedFeatures = ref([]); // 已放置的五官数组
const selectedFeature = ref(null); // 当前选中的五官
const draggingFeature = ref(null); // 正在拖拽的五官
const isOperating = ref(false); // 全局操作状态：防止旋转和缩放同时触发
const touchStartPos = ref({ x: 0, y: 0 }); // 触摸开始位置
const featureStartPos = ref({ x: 0, y: 0 }); // 五官开始位置（用于旋转）

// 缩放状态
const scaleState = ref({
  isScaling: false,
  isRotating: false,
  startScale: 1.0,
  startX: 0,
  startY: 0,
  featureCenterX: 0,
  featureCenterY: 0,
  startVectorX: 0,
  startVectorY: 0,
  startDistance: 0,
  startRotation: 0,
});

// 控制点拖拽状态
const handleState = ref({
  isDragging: false,
  type: "", // 'scale' 或 'rotate'
  feature: null,
  startHandleX: 0,
  startHandleY: 0,
  startFeatureX: 0,
  startFeatureY: 0,
  startScale: 1.0,
  startRotation: 0,
});

// 缩放比例提示
const scaleTip = ref("");

// 特征类别 - 修改为对应API中的类型编号
const featureCategories = ref([
  { name: "发型", key: "hair", type: 6 },
  { name: "眼睛", key: "eyes", type: 1 },
  { name: "眉毛", key: "eyebrows", type: 2 },
  { name: "鼻子", key: "nose", type: 3 },
  { name: "嘴巴", key: "mouth", type: 4 },
  { name: "腮红", key: "blush", type: 5 },
]);

// 特征选项数据 - 从API获取
const featureOptionsData = ref([]);

// 当前选中的特征选项
const currentFeatureOptions = computed(() => {
  return featureOptionsData.value[currentFeatureIndex.value] || [];
});

// 获取五官资源列表
const getFeatureList = async (featureType) => {
  try {
    loading.value = true;
    const response = await http.request({
      url: "/faceFeature/page",
      method: "GET",
      data: {
        page: 1,
        limit: 20,
        featureType: featureType,
        status: 1,
        sortBy: "createTime",
        sortOrder: "desc",
      },
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取五官资源成功:", response);

    // 假设接口返回的数据格式为 {records: [...]}，每条记录包含id、name、imageUrl等字段
    const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL || "";

    response.data?.records.forEach((item) => {
      item.featureImageUrl = resourcesUrl + item.featureImageUrl;
    });

    const features = response.data?.records || [];

    return features;
  } catch (error) {
    console.error("获取五官资源失败:", error);
    // 返回模拟数据作为后备
    return [
      {
        id: `${featureType}-1`,
        name: "样式1",
        imgUrl: "/static/images/icon/head01.png",
      },
      {
        id: `${featureType}-2`,
        name: "样式2",
        imgUrl: "/static/images/icon/head02.png",
      },
      {
        id: `${featureType}-3`,
        name: "样式3",
        imgUrl: "/static/images/icon/head03.png",
      },
      {
        id: `${featureType}-4`,
        name: "样式4",
        imgUrl: "/static/images/icon/head04.png",
      },
      {
        id: `${featureType}-5`,
        name: "样式5",
        imgUrl: "/static/images/default-design.png",
      },
    ];
  } finally {
    loading.value = false;
  }
};

// 获取人脸底图详情
const getFaceBaseDetail = async (baseId) => {
  try {
    loading.value = true;
    const response = await http.request({
      url: "/faceBase/info",
      method: "GET",
      data: {
        baseId: baseId,
      },
      header: {
        "Content-Type": "application/json",
      },
    });

    console.log("获取人脸底图详情成功:", response);

    // 假设接口返回的数据格式中包含图片地址
    const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL || "";
    const imgUrl =
      resourcesUrl +
      (response.data?.faceImageUrl || "/static/images/default-design.png");
    return imgUrl;
  } catch (error) {
    console.error("获取人脸底图失败:", error);
  } finally {
    loading.value = false;
  }
};

// 初始化所有特征数据
const initAllFeatures = async () => {
  // 清空现有数据
  featureOptionsData.value = [];

  // 获取每个特征类别的数据
  for (let i = 0; i < featureCategories.value.length; i++) {
    const category = featureCategories.value[i];
    const features = await getFeatureList(category.type);
    featureOptionsData.value[i] = features;

    // 初始化选中项
    selectedOptions.value[i] = 0;
  }
};

// 页面加载时获取参数
onLoad((options) => {
  if (options.avatarId) {
    avatarId.value = options.avatarId;
    // 通过接口获取人脸底图
    loadFaceBaseImage(options.avatarId);
  }
});

// 加载人脸底图
const loadFaceBaseImage = async (baseId) => {
  try {
    const imgUrl = await getFaceBaseDetail(baseId);
    selectedAvatar.value = imgUrl;
  } catch (error) {
    console.error("加载人脸底图失败:", error);
    selectedAvatar.value = "/static/images/default-design.png";
  }
};

// 页面挂载后初始化数据
onMounted(async () => {
  // 初始化所有特征数据
  await initAllFeatures();
});

// 当切换特征类别时，如果该类别没有数据则获取
watch(currentFeatureIndex, async (newIndex) => {
  if (
    !featureOptionsData.value[newIndex] ||
    featureOptionsData.value[newIndex].length === 0
  ) {
    const category = featureCategories.value[newIndex];
    const features = await getFeatureList(category.type);
    featureOptionsData.value[newIndex] = features;

    if (selectedOptions.value[newIndex] === undefined) {
      selectedOptions.value[newIndex] = 0;
    }
  }
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 进入编辑模式
const enterEditMode = () => {
  isEditMode.value = true;
};

// 切换特征类别
const switchFeature = async (index) => {
  if (index === currentFeatureIndex.value) return;

  // 先设置索引，这样在UI上可以立即切换
  currentFeatureIndex.value = index;

  // 如果该类型数据未加载，则加载数据
  if (
    !featureOptionsData.value[index] ||
    featureOptionsData.value[index].length === 0
  ) {
    loading.value = true;
    const category = featureCategories.value[index];
    try {
      const features = await getFeatureList(category.type);
      featureOptionsData.value[index] = features;

      // 确保选中项存在
      if (selectedOptions.value[index] === undefined) {
        selectedOptions.value[index] = 0;
      }
    } catch (error) {
      console.error(`加载${category.name}数据失败:`, error);
    } finally {
      loading.value = false;
    }
  }
};

// 选择特征选项
const selectFeatureOption = (optionIndex) => {
  // 确保选项索引有效
  if (optionIndex >= 0 && optionIndex < currentFeatureOptions.value.length) {
    selectedOptions.value[currentFeatureIndex.value] = optionIndex;

    // 将选中的五官添加到设计区域
    addFeatureToDesign(currentFeatureOptions.value[optionIndex]);

    console.log(
      `已选择${featureCategories.value[currentFeatureIndex.value].name}:`,
      currentFeatureOptions.value[optionIndex].name
    );
  }
};

// 添加五官到设计区域
const addFeatureToDesign = (featureOption) => {
  const category = featureCategories.value[currentFeatureIndex.value];
  const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL || "";

  // 检查是否已存在相同类型的五官
  const existingIndex = placedFeatures.value.findIndex(
    (f) => f.featureType === category.type
  );

  const newFeature = {
    configId: `feature-${Date.now()}`,
    featureId: featureOption.id || Math.floor(Math.random() * 1000),
    featureName: featureOption.name || featureOption.featureName,
    featureType: category.type,
    imageUrl: featureOption.featureImageUrl || featureOption.imgUrl || "",
    offsetX: 250 + (existingIndex === -1 ? Math.random() * 50 : 0), // 默认居中位置
    offsetY: 250 + (existingIndex === -1 ? Math.random() * 50 : 0),
    scale: 1.0,
    rotation: 0.0,
    layerOrder: placedFeatures.value.length + 1,
    visible: true,
    opacity: 1.0,
    blendMode: "normal",
    filter: {
      brightness: 0,
      contrast: 0,
      saturation: 0,
      hue: 0,
      blur: 0,
      grayscale: false,
      invert: false,
    },
  };

  if (existingIndex !== -1) {
    // 替换已存在的同类型五官
    placedFeatures.value[existingIndex] = newFeature;
  } else {
    // 添加新五官
    placedFeatures.value.push(newFeature);
  }

  // 自动选中刚添加的五官
  selectedFeature.value = newFeature;
};

// 五官触摸事件 - 编辑模式下默认移动
const onFeatureTouchStart = (event, feature) => {
  if (!isEditMode.value) return;

  // 如果已有操作在进行，不允许开始拖拽
  if (isOperating.value) return;

  event.stopPropagation();
  selectFeature(feature);

  const touch = event.touches[0];
  touchStartPos.value = { x: touch.clientX, y: touch.clientY };
  featureStartPos.value = { x: feature.offsetX, y: feature.offsetY };
  draggingFeature.value = feature;

  // 延迟设置操作状态，避免与旋转/缩放冲突
  setTimeout(() => {
    if (draggingFeature.value && !scaleState.isScaling) {
      isOperating.value = true;
    }
  }, 100);
};

const onFeatureTouchMove = (event, feature) => {
  if (!isEditMode.value || !draggingFeature.value) return;

  event.stopPropagation();

  const touch = event.touches[0];
  const deltaX = touch.clientX - touchStartPos.value.x;
  const deltaY = touch.clientY - touchStartPos.value.y;

  // 如果在缩放模式，处理缩放逻辑
  if (scaleState.isScaling) {
    // 计算拖拽距离（综合X和Y方向）
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    const sensitivity = 0.01; // 缩放灵敏度

    // 根据拖拽方向决定缩放方向（向上拖拽放大，向下拖拽缩小）
    const direction = deltaY < 0 ? 1 : -1;
    const scaleDelta = distance * sensitivity * direction;

    let newScale = scaleState.startScale + scaleDelta;

    // 移除缩放限制，允许任意缩放
    // newScale = Math.max(0.3, Math.min(3.0, newScale));

    feature.scale = newScale;

    // 显示缩放比例提示
    scaleTip.value = `${Math.round(newScale * 100)}%`;
    console.log(`缩放中: ${feature.featureName}, 缩放比例: ${newScale}`);
    return;
  }

  // 编辑模式下默认就是移动
  feature.offsetX = featureStartPos.value.x + deltaX;
  feature.offsetY = featureStartPos.value.y + deltaY;
};

const onFeatureTouchEnd = (event, feature) => {
  if (!isEditMode.value) return;

  event.stopPropagation();

  // 如果在缩放模式，处理缩放结束逻辑
  if (scaleState.isScaling) {
    scaleState.isScaling = false;
    scaleTip.value = ""; // 隐藏缩放比例提示

    // 保存配置变更
    saveFeatureConfig();
    console.log(
      `缩放结束: ${feature.featureName}, 最终缩放比例: ${feature.scale}`
    );
  }

  draggingFeature.value = null;
  isOperating.value = false; // 清除操作状态

  // 保存配置变更
  saveFeatureConfig();
};

// 选择五官
const selectFeature = (feature) => {
  if (!isEditMode.value) return;
  selectedFeature.value = feature;
};

// 删除五官
const onDeleteFeature = (event, feature) => {
  event.stopPropagation();

  uni.showModal({
    title: "确认删除",
    content: "确定要删除这个五官吗？",
    success: (res) => {
      if (res.confirm) {
        // 从数组中移除
        const index = placedFeatures.value.findIndex(
          (f) => f.configId === feature.configId
        );
        if (index > -1) {
          placedFeatures.value.splice(index, 1);
        }

        // 清空选中状态
        if (
          selectedFeature.value &&
          selectedFeature.value.configId === feature.configId
        ) {
          selectedFeature.value = null;
        }

        saveFeatureConfig();

        uni.showToast({
          title: "已删除",
          icon: "none",
          duration: 500,
        });
      }
    },
  });
};

// 处理缩放开始 - 同时支持缩放和旋转
const onScaleStart = (event, feature) => {
  if (scaleState.isScaling || scaleState.isRotating) return;

  event.preventDefault();
  event.stopPropagation();

  const touch = event.touches[0];

  // 计算特征中心坐标
  const featureCenterX = feature.offsetX + (80 * feature.scale) / 2;
  const featureCenterY = feature.offsetY + (80 * feature.scale) / 2;

  // 计算初始向量
  const diff_x = touch.clientX - featureCenterX;
  const diff_y = touch.clientY - featureCenterY;

  // 设置状态 - 同时启用缩放和旋转
  scaleState.isScaling = true;
  scaleState.isRotating = true;
  scaleState.startVectorX = diff_x;
  scaleState.startVectorY = diff_y;
  scaleState.startScale = feature.scale;
  scaleState.startRotation = feature.rotation;
  scaleState.featureCenterX = featureCenterX;
  scaleState.featureCenterY = featureCenterY;

  draggingFeature.value = feature;
  isOperating.value = true;

  // 清除之前的动画帧
  if (moveAnimationFrame) {
    cancelAnimationFrame(moveAnimationFrame);
    moveAnimationFrame = null;
  }

  console.log("缩放旋转开始 - 初始缩放:", feature.scale, "初始角度:", feature.rotation);
};

// 处理旋转开始 - 合并到缩放功能中，右下角控制点同时支持缩放和旋转

// 处理缩放移动 - 同时处理缩放和旋转（平滑优化）
let moveAnimationFrame = null;
const handleScaleMove = (event) => {
  if (!scaleState.isScaling && !scaleState.isRotating) return;

  event.stopPropagation();
  const moveTouch = event.touches[0];
  const feature = draggingFeature.value;

  if (!feature) return;

  // 使用requestAnimationFrame进行平滑处理
  if (moveAnimationFrame) return;

  moveAnimationFrame = requestAnimationFrame(() => {
    // 计算特征中心坐标
    const featureCenterX = feature.offsetX + (80 * feature.scale) / 2;
    const featureCenterY = feature.offsetY + (80 * feature.scale) / 2;

    // 同时处理缩放和旋转
    if (scaleState.isScaling && scaleState.isRotating) {
      const diff_x_before = scaleState.startVectorX;
      const diff_y_before = scaleState.startVectorY;
      const diff_x_after = moveTouch.clientX - featureCenterX;
      const diff_y_after = moveTouch.clientY - featureCenterY;

      // 计算缩放
      const distance_before = Math.sqrt(
        diff_x_before * diff_x_before + diff_y_before * diff_y_before
      );
      const distance_after = Math.sqrt(
        diff_x_after * diff_x_after + diff_y_after * diff_y_after
      );

      const scale_ratio = distance_after / distance_before;
      const sensitivity = 0.2; // 降低灵敏度到0.2，更平滑
      const smooth_ratio = 1 + (scale_ratio - 1) * sensitivity;
      const new_scale = smooth_ratio * scaleState.startScale;
      feature.scale = Math.max(0.3, Math.min(3.0, new_scale));

      // 计算旋转 - 使用更平滑的算法
      const angle_before = (Math.atan2(diff_y_before, diff_x_before) * 180) / Math.PI;
      const angle_after = (Math.atan2(diff_y_after, diff_x_after) * 180) / Math.PI;
      const sensitivity_rotate = 0.3; // 降低旋转灵敏度到0.3
      const angle_delta = (angle_after - angle_before) * sensitivity_rotate;
      feature.rotation = angle_delta + scaleState.startRotation;

      // 显示实时信息
      scaleTip.value = `${Math.round(feature.scale * 100)}% ${Math.round(feature.rotation)}°`;
    }

    moveAnimationFrame = null;
  });
};

// 处理缩放和旋转结束
const handleScaleEnd = (event) => {
  if (!scaleState.isScaling && !scaleState.isRotating) return;

  event.preventDefault();
  event.stopPropagation();

  // 清除动画帧
  if (moveAnimationFrame) {
    cancelAnimationFrame(moveAnimationFrame);
    moveAnimationFrame = null;
  }

  // 一次性重置所有状态
  scaleState.isScaling = false;
  scaleState.isRotating = false;
  draggingFeature.value = null;
  isOperating.value = false;
  scaleTip.value = "";

  // 保存配置
  saveFeatureConfig();

  console.log("缩放旋转结束");
};

// 处理旋转移动 - 已合并到handleScaleMove，此函数不再使用
const onRotateMove = (event) => {
  // 旋转功能已合并到缩放功能中，此函数保留但不再执行实际操作
  return;
};

// 控制点触摸开始 - 防止事件冒泡
const onControlTouchStart = (event) => {
  // 阻止事件冒泡，防止触发父元素的触摸事件
  event.stopPropagation();
};


// 层级管理
const bringToFront = () => {
  if (!selectedFeature.value) return;

  // 找到当前最大层级
  const maxLayer = Math.max(...placedFeatures.value.map((f) => f.layerOrder));
  selectedFeature.value.layerOrder = maxLayer + 1;

  // 重新排序
  placedFeatures.value.sort((a, b) => a.layerOrder - b.layerOrder);

  saveFeatureConfig();

  // 添加视觉反馈
  uni.showToast({
    title: "已前置",
    icon: "none",
    duration: 500,
  });
};

const sendToBack = () => {
  if (!selectedFeature.value) return;

  // 找到当前最小层级
  const minLayer = Math.min(...placedFeatures.value.map((f) => f.layerOrder));
  selectedFeature.value.layerOrder = minLayer - 1;

  // 重新排序
  placedFeatures.value.sort((a, b) => a.layerOrder - b.layerOrder);

  saveFeatureConfig();

  // 添加视觉反馈
  uni.showToast({
    title: "已后置",
    icon: "none",
    duration: 500,
  });
};

// 退出编辑模式
const exitEditMode = () => {
  isEditMode.value = false;
  selectedFeature.value = null;
  draggingFeature.value = null;
};

// 保存五官配置
const saveFeatureConfig = () => {
  // 这里可以将配置保存到本地存储或发送到服务器
  console.log("保存五官配置:", placedFeatures.value);

  // 可以在这里添加自动保存到后端的逻辑
  // debouncedSaveToServer();
};

// 监听配置变化，自动保存
watch(
  placedFeatures,
  () => {
    saveFeatureConfig();
  },
  { deep: true }
);

// 防抖的保存函数
const debouncedSaveToServer = debounce(() => {
  if (!selectedFeature.value) return;

  // 这里可以添加调用后端保存接口的逻辑
  console.log("自动保存到服务器...");
}, 1000);

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// 完成设计
const completeDesign = async () => {
  // 先让用户输入设计稿名称
  uni.showModal({
    title: "完成设计",
    content: "请输入设计稿名称",
    editable: true,
    placeholderText: "请输入设计稿名称",
    success: async (res) => {
      if (res.confirm && res.content) {
        const designName = res.content.trim();
        if (designName) {
          await saveDesignToServer(designName);
        } else {
          uni.showToast({
            title: "设计稿名称不能为空",
            icon: "none",
          });
        }
      }
    },
  });
};

// 保存设计稿到服务器
const saveDesignToServer = async (designName) => {
  try {
    loading.value = true;

    // 构建保存参数
    const saveParams = buildSaveParams(designName);

    // 调用保存接口
    const response = await http.request({
      url: "/p/faceDesign/save",
      method: "POST",
      data: saveParams,
      header: {
        "Content-Type": "application/json",
      },
    });

    // 保存成功
    uni.showToast({
      title: "作品已成功保存",
      icon: "success",
    });

    // 可以跳转到设计稿列表页或其他页面
    // uni.navigateTo({ url: '/pages/design/list' });

    console.log("设计稿保存成功:", response);
    return response.data;
  } catch (error) {
    console.error("保存设计稿失败:", error);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
    });
    throw error;
  } finally {
    loading.value = false;
  }
};

// 构建保存参数
const buildSaveParams = (designName) => {
  const currentTime = new Date().toLocaleString("zh-CN");

  // 构建faceBase对象
  const faceBase = {
    faceBaseId: parseInt(avatarId.value) || 3,
    faceName: "基础脸型",
    imageUrl: selectedAvatar.value,
    faceType: 2,
    scale: 1.0,
    offsetX: 0,
    offsetY: 0,
    rotation: 0.0,
  };

  // 构建features数组，使用placedFeatures中的变换参数
  const features = placedFeatures.value.map((feature, index) => ({
    configId: feature.configId || `feature-${index}`,
    featureId: feature.featureId,
    featureName: feature.featureName,
    featureType: feature.featureType,
    imageUrl: feature.imageUrl,
    offsetX: feature.offsetX || 0,
    offsetY: feature.offsetY || 0,
    scale: feature.scale || 1.0,
    rotation: feature.rotation || 0.0,
    layerOrder: feature.layerOrder || index + 1,
    visible: feature.visible !== false,
    opacity: feature.opacity || 1.0,
    blendMode: feature.blendMode || "normal",
    filter: feature.filter || {
      brightness: 0,
      contrast: 0,
      saturation: 0,
      hue: 0,
      blur: 0,
      grayscale: false,
      invert: false,
    },
  }));

  // 构建canvas对象
  const canvas = {
    width: 800,
    height: 600,
    backgroundColor: "#FFFFFF",
    backgroundImage: "",
    zoom: 1.0,
    panX: 0,
    panY: 0,
  };

  // 构建metadata对象
  const metadata = {
    version: "1.0",
    createTime: currentTime,
    lastModified: currentTime,
    author: "当前用户",
    tags: ["自定义", "头像"],
    description: designName,
    thumbnailUrl: "",
  };

  // 返回完整的保存参数
  return {
    designName: designName,
    faceBaseId: parseInt(avatarId.value) || 3,
    featureConfig: {
      faceBase: faceBase,
      features: features,
      canvas: canvas,
      metadata: metadata,
    },
    thumbnailUrl: "",
    designStatus: 1,
    isPublic: 1,
    viewCount: 0,
    likeCount: 0,
  };
};

// 预览定制效果
const previewCustomization = () => {
  uni.showToast({
    title: "预览功能开发中",
    icon: "none",
  });
};

// 显示帮助信息
const showHelp = () => {
  uni.showModal({
    title: "使用帮助",
    content:
      "1. 选择不同的五官特征，打造专属头像\n2. 点击头像区域进入编辑模式\n3. 编辑模式下：\n   - 左上角🗑️ 可删除五官\n   - 右上角🔄 拖拽旋转图标可调整任意角度\n   - 右下角🔍 拖拽缩放图标可调整任意大小\n   - 拖动五官中间区域可移动位置",
    showCancel: false,
  });
};

// 分享定制作品
const shareCustomization = () => {
  uni.showToast({
    title: "分享功能开发中",
    icon: "none",
  });
};

// 清空设计
const clearDesign = () => {
  uni.showModal({
    title: "提示",
    content: "确定要清空当前设计吗？",
    success: (res) => {
      if (res.confirm) {
        // 重置所有选中的选项
        selectedOptions.value = selectedOptions.value.map(() => 0);
        uni.showToast({
          title: "已清空",
          icon: "success",
        });
      }
    },
  });
};
</script>

<style scoped lang="scss">
.customize-container {
  background: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  height: 100rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.edit-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #fafafa;
  border-bottom: 1rpx solid #e6e6e6;
}

.toolbar-section {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.tool-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8rpx 16rpx;
  background-color: #fff;
  border-radius: 8rpx;
  border: 1rpx solid #d9d9d9;
  transition: all 0.2s ease;
}

.tool-btn:active {
  transform: scale(0.96);
}

.tool-btn:disabled {
  opacity: 0.5;
  pointer-events: none;
}

.tool-btn.primary {
  background-color: #1b7dec;
  color: #fff;
  border-color: #1b7dec;
}

.tool-btn.primary:active {
  background-color: #1669c7;
}

.tool-icon {
  font-size: 28rpx;
  margin-bottom: 4rpx;
  color: inherit;
}

.tool-label {
  font-size: 18rpx;
  color: inherit;
  font-weight: 500;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.complete-btn {
  padding: 0 20rpx;
  height: 60rpx;
  background-color: #1b7dec;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.complete-text {
  font-size: 28rpx;
  color: #fff;
}

.side-title {
  padding: 20rpx 30rpx;
}

.title-text {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.avatar-preview-wrapper {
  display: flex;
  padding: 0 30rpx;
  margin-bottom: 40rpx;
}

.avatar-preview {
  width: 80%;
  height: 550rpx;
  background-color: #000;
  border-radius: 20rpx;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.draggable-feature {
  position: absolute;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid transparent;
  border-radius: 10rpx;
  transform-origin: center;
  cursor: move;
  user-select: none;
  -webkit-user-select: none;
}

.draggable-feature.active {
  border-color: #1b7dec;
  box-shadow: 0 0 20rpx rgba(27, 125, 236, 0.5);
}

.draggable-feature.dragging {
  z-index: 9999 !important;
  box-shadow: 0 0 30rpx rgba(27, 125, 236, 0.8);
}

.feature-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.feature-placeholder {
  font-size: 24rpx;
  color: #999;
  text-align: center;
}

.feature-controls {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  pointer-events: none;
}

.control-point {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #1b7dec;
  border: 3rpx solid #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
  transition: all 0.2s ease;
  pointer-events: auto;
  /* 移除相对定位，使用内联样式控制位置 */
}

.control-point:active {
  transform: scale(1.1);
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.4);
}

.control-icon {
  font-size: 20rpx;
  color: #fff;
  pointer-events: none;
}

.delete-point {
  background-color: #f44336;
}

.rotate-point {
  background-color: #ff9800;
}

.scale-point {
  background-color: #4caf50;
}

.avatar-img {
  width: 80%;
  height: 80%;
}

.default-head {
  width: 600rpx;
  height: 600rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.default-head-img {
  width: 100%;
  height: 100%;
}

.preview-tip {
  position: absolute;
  bottom: 20rpx;
  left: 0;
  right: 0;
  text-align: center;
}

.tip-text {
  font-size: 24rpx;
  color: #fff;
}

/* 缩放比例提示 */
.scale-tip {
  position: absolute;
  top: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  z-index: 1000;
}

.scale-tip-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: bold;
}

/* 操作提示样式 */
.operation-tips {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  right: 10rpx;
  display: flex;
  justify-content: center;
  gap: 20rpx;
  flex-wrap: wrap;
  z-index: 900;
}

.tip-item {
  font-size: 20rpx;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.side-functions {
  margin-left: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.function-item {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.function-icon {
  font-size: 36rpx;
  margin-bottom: 10rpx;
}

.function-label {
  font-size: 20rpx;
  color: #666;
}

.customize-options {
  padding: 0 30rpx;
}

.feature-tabs {
  white-space: nowrap;
  margin-bottom: 30rpx;
}

.feature-tab {
  display: inline-block;
  padding: 15rpx 30rpx;
  margin-right: 20rpx;
  background-color: #f5f5f5;
  border-radius: 20rpx;
}

.feature-tab.active {
  background-color: #1b7dec;
}

.feature-tab-text {
  font-size: 28rpx;
  color: #666;
}

.feature-tab.active .feature-tab-text {
  color: #fff;
}

.feature-options {
  white-space: nowrap;
  margin-bottom: 30rpx;
}

.feature-option {
  display: inline-block;
  margin-right: 30rpx;
  text-align: center;
}

.option-preview {
  width: 120rpx;
  height: 120rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.feature-option.active .option-preview {
  border: 2rpx solid #1b7dec;
}

.option-img {
  width: 80%;
  height: 80%;
}

.option-placeholder {
  font-size: 24rpx;
  color: #999;
}

.option-name {
  font-size: 24rpx;
  color: #666;
}

.clear-btn {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-text {
  font-size: 32rpx;
  color: #666;
}

.empty-options {
  padding: 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.loading-container {
  height: 200rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 28rpx;
}
</style>
